﻿using UnityEngine;
using System.Collections;
[RequireComponent(typeof(UILabel))]
public class RollScores : MonoBehaviour {

	UILabel _countsLabel;
	int   TargetScore;
	float NowScore;
	public float CountsTime = 1.2f;
	float CountsSpeed;
	float AddCounts;


	void Awake(){

		_countsLabel = GetComponent<UILabel> ();
		InitState ();
	}

	FSM _state;
	StatePath _sleep = new StatePath("Sleep");
	StatePath _counts = new StatePath("Counts");

	void InitState(){
		_state = new FSM ();
		_state.AddState (_sleep, OnSleepEnter);
		_state.AddState (_counts, OnCountsEnter, OnCountsUpdate);
	}

	void OnSleepEnter(){

	}

	void OnCountsEnter(){

		CountsSpeed = (TargetScore - NowScore) / CountsTime;
	}

	void OnCountsUpdate(float dt){
		AddCounts = CountsSpeed * dt;
		NowScore += AddCounts;
		UpdateValue ((int)NowScore);
		if ((CountsSpeed >= 0 && NowScore >= TargetScore) || (CountsSpeed <= 0 && NowScore <= TargetScore)) {
			NowScore = (int)TargetScore;
			UpdateValue (TargetScore);
			_state.SetState (_sleep);
		}
	}

	void Update(){

		_state.UpdateState (Time.deltaTime);
	}

	public void SetTarget(int Tar){

		TargetScore = Tar;
		_state.SetState (_counts);
	}

	void UpdateValue(int value){
       // Debug.Log("new score: " + NowScore);
		_countsLabel.text = (value).ToString();
	}


}
